﻿using Autofac;
using System;

namespace CommonDevelop.Ioc
{
    /// <summary>
    /// Autofac解析器
    /// </summary>
    public class AutofacDependencyResolver : IDependencyResolver
    {
        public ILifetimeScope CurrScope { get; private set; }
        /// <summary>
        /// 方法注入Autofac容器接口
        /// </summary>
        public void SetContainer(ILifetimeScope scope)
        {
            this.CurrScope = scope;
        }

        public T Resolve<T>()
        {
            return this.CurrScope.Resolve<T>();
        }

        public T Resolve<T>(string serviceName)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
                return default(T);

            return this.CurrScope.ResolveNamed<T>(serviceName);
        }

        public object Resolve(Type type)
        {
            if (type == null)
                return null;

            return this.CurrScope.Resolve(type);
        }

        public object Resolve(string serviceName, Type serviceType)
        {
            if (string.IsNullOrWhiteSpace(serviceName) || serviceType == null)
                return null;

            return this.CurrScope.ResolveNamed(serviceName, serviceType);
        }
    }
}
